<template>
  <view class="calculator-container">
    <view class="calculator">
      <!-- 历史记录显示屏 -->
      <view class="history-display">
        <text class="history-text">{{ historyExpression || '' }}</text>
      </view>
      
      <!-- 主显示屏 -->
      <view class="main-display">
        <text :class="['result-text', { 'result-large': showResult }]">{{ currentDisplay }}</text>
      </view>
      
      <!-- 按钮区域（重新排列，把退格放在左上角） -->
      <view class="buttons">
        <!-- 第一行：退格、正负、百分比、除法 -->
        <view class="button function" @tap="handleBackspace">
          <text class="backspace-text">⌫</text>
        </view>
        <view 
          v-for="(button, index) in topRowButtons" 
          :key="index"
          :class="['button', button.type]"
          @tap="handleButtonClick(button)"
        >
          {{ button.label }}
        </view>
        
        <!-- 其余按钮保持不变 -->
        <view 
          v-for="(button, index) in remainingButtons" 
          :key="'remaining-' + index"
          :class="[
            'button', 
            button.type,
            { 'zero-button': button.label === '0' }
          ]"
          @tap="handleButtonClick(button)"
        >
          {{ button.label }}
        </view>
      </view>
    </view>
    
    <!-- 返回按钮 -->
    <view class="back-button" @tap="navigateBack">
      <text class="back-text">返回</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

// 响应式数据
const historyExpression = ref('')
const currentValue = ref('')
const previousValue = ref(null)
const operation = ref(null)
const waitingForNewValue = ref(false)
const showResult = ref(false)

// 按钮配置（重新分组）
const topRowButtons = [
  { label: '±', type: 'function' },
  { label: '%', type: 'function' },
  { label: '÷', type: 'operator' }
]

const remainingButtons = [
  { label: '7', type: 'number' },
  { label: '8', type: 'number' },
  { label: '9', type: 'number' },
  { label: '×', type: 'operator' },
  
  { label: '4', type: 'number' },
  { label: '5', type: 'number' },
  { label: '6', type: 'number' },
  { label: '−', type: 'operator' },
  
  { label: '1', type: 'number' },
  { label: '2', type: 'number' },
  { label: '3', type: 'number' },
  { label: '+', type: 'operator' },
  
  { label: '0', type: 'number' },
  { label: '.', type: 'number' },
  { label: '=', type: 'operator' }
]

// 计算当前显示内容
const currentDisplay = computed(() => {
  if (currentValue.value === '' && !showResult.value) return '0'
  return showResult.value ? `=${currentValue.value}` : currentValue.value
})

// 导航回首页
const navigateBack = () => {
  uni.navigateBack()
}

// 处理退格
const handleBackspace = () => {
  if (showResult.value) {
    // 如果显示结果，退格清空重新开始
    historyExpression.value = ''
    currentValue.value = ''
    previousValue.value = null
    operation.value = null
    waitingForNewValue.value = false
    showResult.value = false
    return
  }
  
  if (!waitingForNewValue.value && currentValue.value.length > 0) {
    // 删除当前输入的最后一个字符
    currentValue.value = currentValue.value.slice(0, -1)
  } else if (operation.value) {
    // 如果刚输入运算符，取消运算符回到前一个状态
    operation.value = null
    waitingForNewValue.value = false
    currentValue.value = previousValue.value.toString()
    previousValue.value = null
  }
  
  // 更新历史表达式
  updateHistoryExpression()
}

// 处理按钮点击
const handleButtonClick = (button) => {
  const { label, type } = button
  
  switch (type) {
    case 'number':
      handleNumberInput(label)
      break
    case 'operator':
      handleOperatorInput(label)
      break
    case 'function':
      handleFunctionInput(label)
      break
  }
}

// 处理数字输入
const handleNumberInput = (value) => {
  if (showResult.value) {
    // 如果刚刚显示结果，开始新的计算
    historyExpression.value = ''
    currentValue.value = ''
    previousValue.value = null
    operation.value = null
    showResult.value = false
  }
  
  if (waitingForNewValue.value) {
    currentValue.value = ''
    waitingForNewValue.value = false
  }
  
  if (value === '.' && currentValue.value.includes('.')) {
    return
  }
  
  if (value === '.' && currentValue.value === '') {
    currentValue.value = '0.'
  } else {
    currentValue.value += value
  }
  
  // 更新历史表达式
  updateHistoryExpression()
}

// 处理运算符输入
const handleOperatorInput = (op) => {
  if (op === '=') {
    if (previousValue.value !== null && operation.value) {
      const result = calculate(previousValue.value, parseFloat(currentValue.value), operation.value)
      
      // 完成计算，显示结果
      historyExpression.value = `${previousValue.value} ${operation.value} ${currentValue.value}`
      currentValue.value = result.toString()
      showResult.value = true
      
      // 重置状态
      previousValue.value = null
      operation.value = null
      waitingForNewValue.value = true
    }
  } else {
    if (showResult.value) {
      // 如果刚刚显示结果，使用结果作为新计算的开始
      showResult.value = false
      previousValue.value = parseFloat(currentValue.value)
      historyExpression.value = currentValue.value
    } else if (previousValue.value === null) {
      previousValue.value = parseFloat(currentValue.value)
      historyExpression.value = currentValue.value
    } else if (operation.value) {
      // 连续运算
      const result = calculate(previousValue.value, parseFloat(currentValue.value), operation.value)
      previousValue.value = result
      currentValue.value = result.toString()
      historyExpression.value = `${historyExpression.value} ${operation.value} ${currentValue.value}`.replace(/=/g, '')
    }
    
    operation.value = op
    waitingForNewValue.value = true
    
    // 更新历史表达式
    if (!showResult.value) {
      updateHistoryExpression()
    }
  }
}

// 处理功能按钮输入
const handleFunctionInput = (func) => {
  const currentVal = parseFloat(currentValue.value)
  
  switch (func) {
    case 'AC':
      currentValue.value = ''
      historyExpression.value = ''
      previousValue.value = null
      operation.value = null
      waitingForNewValue.value = false
      showResult.value = false
      break
    case '±':
      if (currentValue.value !== '') {
        currentValue.value = (-currentVal).toString()
        updateHistoryExpression()
      }
      break
    case '%':
      if (currentValue.value !== '') {
        currentValue.value = (currentVal / 100).toString()
        updateHistoryExpression()
      }
      break
  }
}

// 更新历史表达式
const updateHistoryExpression = () => {
  let expression = ''
  
  if (previousValue.value !== null) {
    expression += previousValue.value
  }
  
  if (operation.value) {
    expression += ' ' + operation.value
  }
  
  if (currentValue.value !== '' && !waitingForNewValue.value && operation.value) {
    expression += ' ' + currentValue.value
  } else if (currentValue.value !== '' && !operation.value && !previousValue.value) {
    expression = currentValue.value
  }
  
  historyExpression.value = expression
}

// 计算结果
const calculate = (a, b, op) => {
  switch (op) {
    case '+': return a + b
    case '−': return a - b
    case '×': return a * b
    case '÷': return b !== 0 ? a / b : 0
    default: return b
  }
}
</script>

<style lang="scss" scoped>
.calculator-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx 20rpx;
  box-sizing: border-box;
}

.calculator {
  width: 100%;
  max-width: 750rpx;
  background-color: #000;
  border-radius: 60rpx;
  padding: 60rpx 40rpx 80rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}

.history-display {
  width: 100%;
  min-height: 80rpx;
  max-height: 160rpx;
  color: rgba(255, 255, 255, 0.7);
  font-size: 48rpx;
  text-align: right;
  padding: 20rpx 20rpx 10rpx;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.main-display {
  width: 100%;
  height: 150rpx;
  padding: 10rpx 20rpx 30rpx;
  margin-bottom: 40rpx;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.result-text {
  color: #fff;
  font-size: 90rpx;
  font-weight: 300;
  transition: all 0.3s ease;
  
  &.result-large {
    font-size: 110rpx;
    font-weight: 400;
  }
}

.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 25rpx;
}

.button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 150rpx;
  border-radius: 75rpx;
  font-size: 52rpx;
  font-weight: 400;
  transition: all 0.1s;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  
  &:active {
    transform: scale(0.96);
    opacity: 0.8;
  }
  
  &.number {
    background-color: #333;
    color: #fff;
    
    &:active {
      background-color: #555;
    }
  }
  
  &.function {
    background-color: #a6a6a6;
    color: #000;
    
    &:active {
      background-color: #d9d9d9;
    }
  }
  
  &.operator {
    background-color: #ff9f0a;
    color: #fff;
    
    &:active {
      background-color: #ffb143;
    }
  }
  
  &.zero-button {
    grid-column: span 2;
    justify-content: flex-start;
    padding-left: 70rpx;
    border-radius: 75rpx;
  }
}

.backspace-text {
  font-size: 60rpx;
  font-weight: 300;
}

.back-button {
  margin-top: 60rpx;
  padding: 25rpx 80rpx;
  background-color: #007aff;
  color: white;
  border-radius: 50rpx;
  box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.2);
  
  &:active {
    background-color: #0056cc;
    transform: translateY(2rpx);
  }
}

.back-text {
  font-size: 36rpx;
  font-weight: 500;
}

/* 适配横屏 */
@media (min-width: 768px) {
  .calculator {
    max-width: 500rpx;
  }
  
  .history-display {
    font-size: 40rpx;
    min-height: 60rpx;
  }
  
  .result-text {
    font-size: 75rpx;
    
    &.result-large {
      font-size: 90rpx;
    }
  }
  
  .button {
    height: 130rpx;
    font-size: 45rpx;
  }
}
</style>